using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using LitJson;


public class IapKitBuildProcessor : IPostprocessBuildWithReport
{
    public int callbackOrder
    {
        get { return 10; }
    }

    /**
    * build 构建完成后回调
    */
    public void OnPostprocessBuild(BuildReport report)
    {
        if (report.summary.platform == BuildTarget.OpenHarmony)
        {
            Debug.Log("Path is :" + report.summary.outputPath);
            CustomRecodeFile(report.summary.outputPath);
        }
    }

    private void CustomRecodeFile(string path)
    {
        ModifyMainWorker(path);
    }

    /**
     * TuanjieMainWorker.cs 新增import和消息监听代码
     */
    private void ModifyMainWorker(string path)
    {
        // 修改 WorkerProxy.ets
        var filePath = path + "/tuanjieLib/src/main/ets/workers/WorkerProxy.ets";
        if (!File.Exists(filePath)) return;
        
        var foOhPackage = new FileOperator(filePath);
        var importLine = "import { SDKManager } from '../entry/handler/SDKManager';";
        foOhPackage.InsertImports(importLine);
        
        var belowCode = "        PROCESS_UI_HANDLER(msg.data);";
        var insertCode = "      } else if (msg.data.type == \"IapKit\") { SDKManager.ProcessOnUI(msg.data);";
        foOhPackage.WriteBelowCode(belowCode, insertCode);
        
        // 修改 HostProxy.ets
        filePath = path + "/tuanjieLib/src/main/ets/workers/HostProxy.ets";
        if (!File.Exists(filePath)) return;
        foOhPackage = new FileOperator(filePath);
        
        foOhPackage.InsertImports(importLine);
        
        belowCode = "    PROCESS_TUANJIE_HANDLER(msg);";
        insertCode = "  } else if (msg.type == \"IapKitResult\") { SDKManager.ProcessOnWorker(msg);";
        foOhPackage.WriteBelowCode(belowCode, insertCode);
    }
}